package com.cal.calonecal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cal.calonecal.common.Response;
import com.cal.calonecal.mapper.ClassRoomMapper;
import com.cal.calonecal.mapper.StudentMapper;
import com.cal.calonecal.mapper.UserInfoMapper;
import com.cal.calonecal.pojo.dto.CreateClassDTO;
import com.cal.calonecal.pojo.entity.ClassRoom;
import com.cal.calonecal.pojo.entity.Student;
import com.cal.calonecal.pojo.entity.UserInfo;
import com.cal.calonecal.service.IClassRoomService;
import com.cal.calonecal.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 76004
 * @apiNote
 * @date 2023/6/10 16:10
 */
@Service
public class ClassRoomService implements IClassRoomService {
    @Autowired
    private ClassRoomMapper classRoomMapper;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public Response<Void> createClass(CreateClassDTO createClassDTO) {
        UserInfo userInfo = userUtil.getUser();
        ClassRoom classRoom = BeanUtil.copyProperties(createClassDTO, ClassRoom.class, "id");
        classRoom.setId(null);
        classRoom.setCreateTime(new Date());
        classRoom.setStatus(0);
        classRoom.setTeacherId(userInfo.getId());
        classRoom.setMaxStudentCnt(500);
        classRoomMapper.insert(classRoom);
        return Response.success();
    }

    @Override
    public Response<IPage<UserInfo>> getStudents(Long classId, Integer pageSize, Integer pageNum) {
        ClassRoom classRoom = classRoomMapper.selectById(classId);
        IPage<Student> students = studentMapper.selectPage(new Page<Student>(pageNum, pageSize), new QueryWrapper<Student>().eq("class_id", classId));
        Page<UserInfo>userInfoIPage = BeanUtil.copyProperties(students, Page.class,"records");
        if(students.getRecords().size() != 0){
            userInfoIPage.setRecords(userInfoMapper.selectBatchIds(students.getRecords().stream().map(Student::getUserId).collect(Collectors.toList())));
        }
        return Response.success(userInfoIPage);
    }

    @Override
    public Response<Void> deleteClass(Long classId) {
        UserInfo userInfo = userUtil.getUser();
        ClassRoom classRoom = classRoomMapper.selectById(classId);
        if(userInfo.getId().equals(classRoom.getTeacherId()) || userInfo.getType() == 3){
            classRoomMapper.deleteById(classId);
        }
        else{
            throw new RuntimeException("无权限");
        }
        return Response.success();
    }

    @Override
    public Response<IPage<ClassRoom>> getClassRooms(Integer pageSize, Integer pageNum, Long userId) {
        if (userId == 0) {
            return Response.success(classRoomMapper.selectPage(new Page<ClassRoom>(pageNum, pageSize),null));
        }
        IPage<Student>students = studentMapper.selectPage(new Page<Student>(pageNum, pageSize), new QueryWrapper<Student>().eq("user_id", userId));

        classRoomMapper.selectList(new QueryWrapper<ClassRoom>().eq("id",
                students.getRecords().stream().map(Student::getClassId).collect(Collectors.toList())));
        Page<ClassRoom> classRoomIPage = BeanUtil.copyProperties(students, Page.class, "records");
        students.getRecords().stream().peek(student -> {
            classRoomIPage.getRecords().add(classRoomMapper.selectById(student.getClassId()));
        }).collect(Collectors.toList());
        return Response.success(classRoomIPage);
    }

    @Override
    public Response<Void> updateClassStatus(Long classId, Integer status) {
        UserInfo userInfo = userUtil.getUser();
        if(status != 1){
            ClassRoom classRoom = classRoomMapper.selectById(classId);
            classRoom.setStatus(status);
            classRoomMapper.updateById(classRoom);
        }
        else if(userInfo.getType() == 2){
            ClassRoom classRoom = classRoomMapper.selectById(classId);
            classRoom.setStatus(status);
            classRoomMapper.updateById(classRoom);
        }
        else{
            throw new RuntimeException("没有权限");
        }
        return Response.success();
    }

    @Override
    public Response<Void> joinClass(Long classId) {
        ClassRoom classRoom = classRoomMapper.selectById(classId);
        Integer count = studentMapper.selectCount(new QueryWrapper<Student>().eq("class_id", classId));
        if(classRoom!=null && classRoom.getStatus() == 0 && count < classRoom.getMaxStudentCnt()){
            Student student = new Student();
            student.setClassId(classId);
            student.setUserId(userUtil.getUserId());
            student.setCreateTime(new Date());
            studentMapper.insert(student);
        }else{
            throw new RuntimeException("无法加入班级，班级人数已满或班级老师拒绝其他人加入或班级不存在");
        }
        return Response.success();
    }

    @Override
    public Response<Void> removeStudent(Long userId, Long classId) {
        ClassRoom classRoom = classRoomMapper.selectById(classId);
        if(classRoom == null){
            throw new RuntimeException("班级不存在");
        }
        UserInfo userInfo = userUtil.getUser();
        if(!Objects.equals(userInfo.getId(), classRoom.getTeacherId())){
            throw new RuntimeException("你没有这么做的权限");
        }
        try{
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("class_id", classId).eq("user_id", userId));
        } catch (Exception e){
            throw new RuntimeException("班级中没有此学生");
        }
        studentMapper.delete(new QueryWrapper<Student>().eq("class_id",classId).eq("user_id", userId));
        return Response.success();
    }

    @Override
    public Response<Void> exitClass(Long classId) {
        UserInfo userInfo = userUtil.getUser();
        studentMapper.delete(new QueryWrapper<Student>().eq("class_id", classId).eq("user_id", userInfo.getId()));
        return Response.success();
    }

    @Override
    public Response<Void> updateClass(ClassRoom classRoom) {
        UserInfo userInfo = userUtil.getUser();
        if(userInfo.getType() == 2 || (userInfo.getType() == 1 && Objects.equals(classRoom.getTeacherId(), userInfo.getId()))){
            classRoomMapper.updateById(classRoom);
        }else{
            throw new RuntimeException("没有权限");
        }
        return Response.success();
    }

    @Override
    public Response<IPage<ClassRoom>> selectByTeacherId(Integer pageNum, Integer pageSize) {
        return Response.success(classRoomMapper.selectPage(new Page<ClassRoom>(pageNum, pageSize), new QueryWrapper<ClassRoom>().eq("teacher_id", userUtil.getUserId())));
    }
}
